<template>
  <div class="ele-body">
    <!-- 数据表格 -->
    <el-card shadow="always" body-style="padding: 30px 40px">
      <el-form :inline="true" :model="formInline" class="demo-form-inline">
        <el-form-item label="关键字：">
          <el-input
            style="width: 400px"
            v-model="formInline.title"
            placeholder="关键字"
          ></el-input>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleSearch">查询</el-button>
          <el-button @click="handleReset">重置</el-button>
          <el-button
            @click="handleOpen"
            style="margin-left: 30px"
            type="primary"
            >新增入库<i class="el-icon-plus el-icon--right"></i
          ></el-button>
        </el-form-item>
      </el-form>
      <el-table :data="tableData" border style="width: 100%">
        <el-table-column type="index" width="100" label="序号">
        </el-table-column>
        <el-table-column prop="inOrderNo" label="入库单号" >
        </el-table-column>
        <el-table-column prop="inDate" label="入库日期" >
          <template slot-scope="scope">
            {{ formatDateTime(scope.row.inDate) }}
          </template>
        </el-table-column>
        <el-table-column prop="statusDesc" label="状态" width="380">
        </el-table-column>
        <el-table-column label="操作" min-width="300">
          <template slot-scope="scope">
            <el-button
              v-if="scope.row.status == 1"
              type="text"
              @click="onEdit(scope.row.id)"
              size="small"
              >编辑</el-button
            >
            <el-popconfirm
              @confirm="onConfirm(scope.row.id)"
              title="这是一段内容确定删除吗？"
            >
              <el-button
                v-if="scope.row.status == 1"
                style="margin-left: 20px; color: red"
                slot="reference"
                type="text"
                size="small"
                >删除</el-button
              >
            </el-popconfirm>
            <el-button
              v-if="scope.row.status == 5"
              type="text"
              @click="seeDetail(scope.row.id)"
              size="small"
              >查看详情</el-button
            >
          </template>
        </el-table-column>
      </el-table>
      <el-pagination
        style="display: flex; justify-content: flex-end"
        background
        @current-change="handleCurrentChange"
        layout="total, prev, pager, next"
        :current-page.sync="currentPage"
        :total="totalNum"
        :page-size="10"
      >
      </el-pagination>
    </el-card>

    <el-dialog
      :close-on-click-modal="false"
      :title="title"
      width="78%"
      :visible.sync="dialogFormVisible"
    >
      <el-form
        ref="ruleForm"
        :rules="rules"
        label-position="right"
        label-width="90px"
        :model="form"
      >
        <el-row :gutter="24" style="margin-bottom: 20px">
          <el-col :span="6">
            <el-form-item label="入库日期" prop="inDate">
              <el-date-picker
                :disabled="title == '入库详情'"
                v-model="form.inDate"
                type="date"
                format="yyyy-MM-dd"
                value-format="yyyy-MM-dd"
                placeholder="选择日期"
              >
              </el-date-picker>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="入库人" prop="inUser">
              <el-select
                :disabled="title == '入库详情'"
                v-model="form.inUser"
                placeholder="请选择"
              >
                <el-option
                  v-for="item in peopleList"
                  :key="item.id"
                  :label="item.realName"
                  :value="item.id"
                >
                </el-option>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>

        <el-form-item label="产品明细">
          <el-button
            type="primary"
            :disabled="title == '入库详情'"
            @click="handleOpenProductDialog"
            >选择产品</el-button
          >
          <el-table max-height="500" style="width: 100%;margin-left: -68px;margin-top: 10px;" :data="form.stockItems" border>
            <el-table-column type="index" width="100" label="序号">
            </el-table-column>

            <el-table-column prop="productCode" label="产品编号" width="120">
            </el-table-column>
            <el-table-column prop="productName" label="产品名称" width="140">
            </el-table-column>
            <el-table-column prop="productItemName" label="规格" width="120">
            </el-table-column>
            <el-table-column prop="qty" label="入库数量" min-width="150">
              <template slot-scope="scope">
                <el-input-number
                  :disabled="title == '入库详情'"
                  v-model="scope.row.qty"
                  :min="1"
                  :max="9999"
                  label="请输入入库数量"
                ></el-input-number>
              </template>
            </el-table-column>
            <el-table-column prop="costPrice" label="入库成本" min-width="150">
              <template slot-scope="scope">
                <el-input-number
                  :disabled="title == '入库详情'"
                  v-model="scope.row.costPrice"
                  :min="0.1"
                  :max="9999"
                  label="请输入入库成本"
                ></el-input-number>
              </template>
            </el-table-column>
            <el-table-column prop="content" label="单位" min-width="120">
              <template slot-scope="scope">
                <el-select
                  :disabled="title == '入库详情'"
                  v-model="scope.row.unitId"
                  placeholder="请选择单位"
                >
                  <el-option
                    v-for="item in dictionaryList"
                    :key="item.id"
                    :label="item.name"
                    :value="item.id"
                  >
                  </el-option>
                </el-select>
              </template>
            </el-table-column>
            <el-table-column prop="content" label="仓库" min-width="120">
              <template slot-scope="scope">
                <el-select
                  :disabled="title == '入库详情'"
                  v-model="scope.row.wareHouseId"
                  placeholder="请选择单位"
                >
                  <el-option
                    v-for="item in warehouseList"
                    :key="item.id"
                    :label="item.name"
                    :value="item.id"
                  >
                  </el-option>
                </el-select>
              </template>
            </el-table-column>
            <el-table-column
              label="操作"
              width="120"
              v-if="title != '入库详情'"
            >
              <template slot-scope="scope">
                <el-button
                  style="margin-left: 20px; color: red"
                  type="text"
                  size="small"
                  @click="deleteProductItem(scope.$index)"
                  >删除</el-button
                >
              </template>
            </el-table-column>
          </el-table>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer" v-if="title !== '入库详情'">
        <el-button @click="dialogFormVisible = false">取 消</el-button>
        <el-button v-if="title === '新增入库'" type="primary" @click="addBanner"
          >确 定</el-button
        >
        <el-button
          v-if="title === '编辑入库'"
          type="primary"
          @click="editBanner"
          >确 定</el-button
        >

        <el-button
          v-if="title === '编辑入库'"
          type="primary"
          @click="examineItem"
          >审核入库</el-button
        >
      </div>
    </el-dialog>

    <el-dialog
      :close-on-click-modal="false"
      title="选择产品"
      width="50%"
      :visible.sync="productDialogFormVisible"
    >
      <el-table
        style="width: 100%"
        height="600"
        :data="productList"
        @selection-change="handleSelectionChange"
        border
      >
        <el-table-column type="selection" width="55" align="center">
        </el-table-column>
        <el-table-column type="index" width="100" label="序号" align="center">
        </el-table-column>

        <el-table-column
          prop="code"
          label="原料编号"
          width="150"
          align="center"
        >
        </el-table-column>
        <el-table-column
          prop="name"
          label="原料名称"
          width="150"
          align="center"
        >
        </el-table-column>
        <el-table-column
          prop="unitName"
          label="单位"
          width="150"
          align="center"
        >
        </el-table-column>
        <el-table-column
          prop="productItemName"
          label="规格"
          min-width="150"
          align="center"
        >
        </el-table-column>
      </el-table>
      <div slot="footer" class="dialog-footer">
        <el-button @click="handleCancel">取 消</el-button>
        <el-button type="primary" @click="handleConfirm">确 定</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import {
  AllPersonnel,
  QueryInStockByCondition,
  DelInStock,
  AddWarehouse,
  UploadFile,
  QueryInStockById,
  UpdateInStock,
  QueryProductJoinItemByCondition,
  QueryAllChildDictViewByCode,
  QueryWarehouseByCondition,
  AddInStock,
  AuitInStock
} from '@/api/invoicingmanager';
export default {
  name: 'Instock',
  data() {
    return {
      productDialogFormVisible: false,
      title: '',
      currentPage: 1,
      totalNum: 0,
      formInline: {
        title: ''
      },
      tableData: [],
      dialogFormVisible: true,
      form: {
        inDate: '',
        inUser: '',
        stockItems: []
      },
      rules: {
        inDate: [
          { required: true, message: '请选择入库日期', trigger: 'change' }
        ],
        inUser: [{ required: true, message: '请选择入库人', trigger: 'change' }]
      },
      itemDeatail: {},
      dictionaryList: [],
      warehouseList: [],
      productList: [],
      selectList: [],
      peopleList: []
    };
  },
  created() {
    this.initData();
    this.getDictionary();
    this.getCk();
    this.getAllUser();
  },
  methods: {
    formatDateTime(isoString) {
      const date = new Date(isoString);
      const year = date.getFullYear();
      const month = date.getMonth() + 1; // 月份从0开始，需+1
      const day = date.getDate();
      const hours = date.getHours().toString().padStart(2, '0');
      const minutes = date.getMinutes().toString().padStart(2, '0');
      const seconds = date.getSeconds().toString().padStart(2, '0');
      return `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`;
    },
    handleCancel() {
      this.selectList = [];
      this.productDialogFormVisible = false;
    },
    handleConfirm() {
      let arr = [];
      this.selectList.forEach((item) => {
        arr.push({
          // ...item,
          productCode: item.code,
          productName: item.name,
          productItemName: item.productItemName,
          productId: item.id,
          productItemId: item.productItemId,
          qty: item.qty,
          salePrice: item.salePrice,
          costPrice: item.costPrice,
          unitId: item.unitId,
          remark: item.remark,
          wareHouseId: item.wareHouseId
        });
      });
      this.$set(this.form, 'stockItems', arr);
      this.productDialogFormVisible = false;
    },
    handleSelectionChange(val) {
      this.selectList = val;
    },
    handleOpenProductDialog() {
      this.productDialogFormVisible = true;
      this.getAllProduct();
    },
    deleteProductItem(index) {
      this.form.stockItems.splice(index, 1);
    },
    handleCurrentChange(val) {
      this.currentPage = val;
      this.initData();
    },
    // 获取仓库
    getCk() {
      QueryWarehouseByCondition({
        pageIndex: 1,
        pageSize: 100,
        conditions: {
          keyword: ''
        },
        orderBys: [
          {
            sort: 'createDate',
            order: 0
          }
        ]
      })
        .then((res) => {
          this.warehouseList = res;
        })
        .catch((e) => {
          this.$message.error(e.message);
        });
    },
    // 获取字典值
    getDictionary() {
      QueryAllChildDictViewByCode({
        code: 'DW'
      }).then((res) => {
        console.log('res>>>>>>>>>>1', res);
        this.dictionaryList = res;
      });
    },
    // 获取所有产品
    getAllProduct() {
      QueryProductJoinItemByCondition({
        pageIndex: 1,
        pageSize: 100000,
        conditions: {
          keyword: '',
          status: ''
        },
        orderBys: [
          {
            sort: 'createDate',
            order: 0
          }
        ]
      })
        .then((res) => {
          console.log('res>>>>>>>>>>2', res);
          this.productList = res.items;
        })
        .catch((e) => {
          this.$message.error(e.message);
        });
    },
    // 获取用户
    getAllUser() {
      AllPersonnel({
        pageindex: 1,
        conditions: [],
        orderBys: [{ sort: 'account', order: 1 }],
        pagesize: 1000
      }).then((res) => {
        this.peopleList = res.items;
        console.log('res>>>>>>>>>>3', res);
      });
    },
    initData() {
      QueryInStockByCondition({
        pageIndex: this.currentPage,
        pageSize: 10,
        conditions: {
          keyword: this.formInline.title
        },
        orderBys: [
          {
            sort: 'createDate',
            order: 0
          }
        ]
      })
        .then((res) => {
          console.log(res);
          this.tableData = res.items;
          this.totalNum = res.totalrecords;
        })
        .catch((e) => {
          this.$message.error(e.message);
        });
    },
    onEdit(id) {
      this.title = '编辑入库';
      this.guid = id;
      this.getDetail(id);
      this.dialogFormVisible = true;
    },
    seeDetail(id) {
      this.title = '入库详情';
      this.guid = id;
      this.getDetail(id);
      this.dialogFormVisible = true;
    },
    getDetail(id) {
      QueryInStockById({
        id: id
      })
        .then((res) => {
          this.form = {
            inDate: res.inDate,
            inUser: res.inUser,
            stockItems: res.stockItems
          };
          this.itemDeatail = res;
        })
        .catch((e) => {
          this.$message.error(e.message);
        });
    },
    editBanner() {
      this.$refs['ruleForm'].validate((valid) => {
        if (valid) {
          for (let i = 0; i < this.form.stockItems.length; i++) {
            if (
              !this.form.stockItems[i].qty ||
              !this.form.stockItems[i].costPrice ||
              !this.form.stockItems[i].unitId ||
              !this.form.stockItems[i].wareHouseId
            ) {
              this.$message.error('请填写完整产品明细信息');
              return false;
            }
          }
          UpdateInStock({
            inDate: this.form.inDate,
            inUser: this.form.inUser,
            stockItems: this.form.stockItems,
            inOrderNo: this.itemDeatail.inOrderNo,
            id: this.guid
          })
            .then((res) => {
              this.$message.success('修改成功');
              this.dialogFormVisible = false;
              this.initData();
            })
            .catch((e) => {
              this.$message.error(e.message);
            });
        } else {
          console.log('error submit!!');
          return false;
        }
      });
    },
    examineItem() {
      this.$refs['ruleForm'].validate((valid) => {
        if (valid) {
          for (let i = 0; i < this.form.stockItems.length; i++) {
            if (
              !this.form.stockItems[i].qty ||
              !this.form.stockItems[i].costPrice ||
              !this.form.stockItems[i].unitId ||
              !this.form.stockItems[i].wareHouseId
            ) {
              this.$message.error('请填写完整产品明细信息');
              return false;
            }
          }
          AuitInStock({
            inDate: this.form.inDate,
            inUser: this.form.inUser,
            stockItems: this.form.stockItems,
            inOrderNo: this.itemDeatail.inOrderNo,
            id: this.guid
          })
            .then((res) => {
              this.$message.success('修改成功');
              this.dialogFormVisible = false;
              this.initData();
            })
            .catch((e) => {
              this.$message.error(e.message);
            });
        } else {
          console.log('error submit!!');
          return false;
        }
      });
    },
    addBanner() {
      this.$refs['ruleForm'].validate((valid) => {
        if (valid) {
          for (let i = 0; i < this.form.stockItems.length; i++) {
            if (
              !this.form.stockItems[i].qty ||
              !this.form.stockItems[i].costPrice ||
              !this.form.stockItems[i].unitId ||
              !this.form.stockItems[i].wareHouseId
            ) {
              this.$message.error('请填写完整产品明细信息');
              return false;
            }
          }
          AddInStock({
            inDate: this.form.inDate,
            inUser: this.form.inUser,
            stockItems: this.form.stockItems
          })
            .then((res) => {
              this.$message.success('新增成功');
              this.dialogFormVisible = false;
              this.initData();
            })
            .catch((e) => {
              this.$message.error(e.message);
            });
        } else {
          console.log('error submit!!');
          return false;
        }
      });
    },
    delItem(id) {
      DelInStock({ id: id })
        .then((res) => {
          this.$message.success('删除成功');
          this.initData();
        })
        .catch((e) => {
          this.$message.error(e.message);
        });
    },
    onConfirm(id) {
      this.delItem(id);
    },
    handleSearch() {
      this.currentPage = 1;
      this.initData();
    },
    handleReset() {
      this.formInline = {};
      this.currentPage = 1;
    },
    handleOpen() {
      this.title = '新增入库';
      this.form = {};
      this.dialogFormVisible = true;
      console.log(this.title);
    }
  }
};
</script>
<style lang="scss" scoped>
.avatar-uploader .el-upload {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
}
.avatar-uploader .el-upload:hover {
  border-color: #409eff;
}
.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  line-height: 178px;
  text-align: center;
}
.avatar {
  width: 178px;
  height: 178px;
  display: block;
}
</style>
